<?php
/**
 * 示例model（标注表的作用）
 * panglishan
 * 2020.08.13
 */
namespace App\Models\MainDB;

use App\Services\Tools\RedisService;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Redis;

class User extends Model{

    protected $table = 'ln_user';     //数据库内完整表名

    protected $primaryKey = 'user_id';    //主键名

    protected $appends = ['exp'];

    protected $fillable = [
        'user_id',      //主键ID
        'mobile',      //手机号码
        'password',      //密码
        'user_no',      //邀请码
        'parent_id',      //上级
        'disabled',      //用户状态 0禁用 1正常
        'register_time',      //注册时间
        'last_login_time',      //上次登陆时间
        'login_count',      //登录次数
        'rank_id',      //等级
        'last_login_ip',      //最后登录ip
        'open_id',      //第三方登录
        'three_party',      //1.微信  2.QQ 3.h5
        'emchat_username',      //环信账号
        'emchat_password',      //环信密码
        'money',      //可用余额
        'freeze_money',      //冻结金额
        'nobility',      //爵位id
        'expiration_time',      //爵位过期时间
        'earnings',      //收益
        'seal_time',      //封禁时间
        'second_password',      //二级密码
        'channel_id',      //渠道id
        'channel_no',      //渠道编号
        'last_online_time',      //最近一次在线时间
        'offline_time',      //离线时间
        'role',      //1普通2官方
        'coin',      //特殊币
        'earnings_coin',      //收益中包含的特殊币
        'energy',      //用户能量值
        'deleted',      //是否被注销：1 是  0否
        'gift_bag_id',      //邀请礼包
        'gift_bag_quantity',      //礼包数量
        'is_seal_money',        // 是否封禁餘額 0否 1是
        'seal_remark',      // 封禁備註
    ];

    public $timestamps = false;


    //关联user_data模型
    public function user_data()
    {
        return $this->hasOne('App\Models\MainDB\UserData', 'user_id', 'user_id');
    }

    //关联渠道模型
    public  function  channel(){

       return $this->hasOne('App\Models\MainDB\Channel','channel_no','channel_no');
    }

    public function stage_user_data(){
        $connection = 'mysql';
        return $this->setConnection($connection)->belongsTo(ChannelUserData::class,'user_id','user_id');
    }

    //关联注销表
    public  function cancel_account(){

        return $this->hasOne('App\Models\MainDB\CancelAccount','user_id','user_id');
    }

    public function getExpAttribute()
    {
        $exp = Redis::get('u:exp:' . $this->user_id);
        if ($exp !== false) {
            return round($exp, 2);
        }
        $exp = app("model_user_exp")->where("user_id", $this->user_id)->sum('exp');
        Redis::setex('u:exp:' . $this->user_id, 604800, $exp);
        return $exp ? round($exp, 2) : 0;
    }

    public function addExp($gold, $exp = 0, $type = 1, $action_id = 0) {
        if ($type == 1) {
            $goldFee = floatval(app('repo_config')->queryConfig('GOLD_FEE')->value);

            $money = round($gold / $goldFee, 2);

            //是否有爵位加速
            $ratio = app("repo_user")->getNobilityRatio($this->user_id);

            $exp = round($money * (1 + $ratio / 100), 2);
        } else {
            $money = 0;
            $ratio = 0;
        }

        app("model_user_exp")->create([
            'user_id'   => $this->user_id,
            'gold'      => $gold,
            'money'     => $money,
            'exp'       => floatval($exp),
            'add_time'  => time(),
            'ratio'     => floatval($ratio),
            'type'      => $type,
            'action_id' => $action_id,
        ]);
        $totalExp = app("model_user_exp")->where("user_id", $this->user_id)->sum('exp');
        Redis::setex('u:exp:' . $this->user_id,604800, $totalExp);

        $this->userUpgrade();
    }

    public function userUpgrade($down = 0) {
        $exp = $this->getExpAttribute();
        $info = app("model_grade_config")->where([
            ["experience", "<=", $exp]
        ])->orderBy('id',"desc")->first();

        if ($info) {
            $user_rank_info = Redis::get('u:rank:' . $this->user_id);
            if ($user_rank_info !== false) {
                $user_rank_map = json_decode($user_rank_info, 1);
                $ori_rank_id = $user_rank_map['rank_id'];
            } else {
                $ori_rank_id = $this->rank_id;
            }
            if (($info->id > $ori_rank_id) || ($info->id < $ori_rank_id && $down == 1)) {
                Redis::del('u:rank:' . $this->user_id);
                $this->rank_id = $info->id;
                $this->save();
            }
        }

        return $info->id ?? 0;
    }

    public function getInfo($fields = '*', $where = [])
    {
        return $this->select($fields)->where($where)->where('deleted', 0)->first();
    }

    //获取某字段的值
    public function getFieldValue($field, $where = [])
    {
        return $this->where($where)->where('deleted', 0)->value($field);
    }

    //关联user_photo模型
    public function user_photo()
    {
        return $this->hasMany('App\Models\MainDB\UserPhoto', 'user_id', 'user_id');
    }

    //关联user_score模型
    public function user_score()
    {
        return $this->hasOne('App\Models\MainDB\UserScore', 'user_id', 'user_id');
    }

    /**
     * @param  int  $register_time  注册时间
     * @return bool 判断是否是新用户 1是0否 注册时间在3天以内 算新用户
     */
    public function userIsNew(int $register_time)
    {
        if ($register_time >= (Carbon::now()->timestamp - 604800)) {
            return 1;
        }

        return 0;
    }

    public function upgradeVip($user_id)
    {
        $total_exp = app('model_user_exp')->getUserExp($user_id);

        $info = app("model_grade_config")->where([
            ["experience", "<=", $total_exp],
        ])->orderBy('id', "desc")->first();

        if ($info) {
            $ori_rank_id = RedisService::getUserBaseInfo($user_id, 'rank_id');
            if ($info->id > $ori_rank_id) {
                app('model_user')->where('user_id', $user_id)->update(['rank_id' => $info->id]);
                RedisService::clearUserInfo($user_id);
            }
        }

        return $info->id ?? 0;
    }
}